package com.itany.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * Author:石小俊
 * Date: 2022/11/2 17:11
 */
public class Test {

    public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException {
        Class c = User.class;

        // 获取类上的注解
        Annotation[] annotations = c.getAnnotations();
        System.out.println("类上的所有注解:"+ Arrays.toString(annotations));

        Annotation someAnnotation = c.getAnnotation(SomeAnnotation.class);
        System.out.println("获取类上指定注解:"+someAnnotation);

        // 获取属性上所有注解
        Field field = c.getDeclaredField("username");
        annotations = field.getAnnotations();
        System.out.println("username属性上的所有注解:"+Arrays.toString(annotations));
        someAnnotation = field.getAnnotation(SomeAnnotation.class);
        System.out.println("属性上指定注解:"+someAnnotation);

        // 获取方法上的所有注解
        Method method = c.getDeclaredMethod("login");
        annotations = method.getAnnotations();
        System.out.println("login方法上的所有注解:"+Arrays.toString(annotations));
        Annotation annotation = method.getAnnotation(OtherAnnotation.class);
        System.out.println("login方法上指定注解:"+annotation);

        // 获取指定注解的属性值
        // 判断当前的注解是否是OtherAnnotation类型
        if(annotation instanceof OtherAnnotation){
            // 如果是, 转换成对应的类型
            OtherAnnotation otherAnnotation = (OtherAnnotation) annotation;
            System.out.println("methods:"+Arrays.toString(otherAnnotation.methods()));
            System.out.println("password:"+otherAnnotation.password());
        }

        // 判断方法是否使用了指定注解
        if(method.isAnnotationPresent(SomeAnnotation.class)){
            System.out.println(method.getName()+"方法使用了SomeAnntation注解");
        }else{
            System.out.println(method.getName()+"方法没有使用SomeAnntation注解");
        }

    }

}
